package com.way2sms.way2inbox;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.provider.Telephony;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.app.ProgressDialog;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuInflater;
import android.view.MotionEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import www.way2inbox.common.PrintMsg;
import www.way2inbox.data.Native_DatabaseHelper;
import www.way2inbox.data.SmsDatabase;
import www.way2inbox.data.smsfetch;
import www.way2inbox.settings.DeviceDetailsClass;


public class PrivateSMS extends ActionBarActivity implements OnItemClickListener,
        View.OnClickListener, TextWatcher, View.OnTouchListener{

    //MAIN LAYOUT ..
    RelativeLayout List_Options,list_menu,searchLayout_edittext;

    //SUBLAYOUT...
    RelativeLayout list_options_back,list_opt_delete,list_opt_spam,list_opt_unprivate,search,Private_back,search_back;

    //Search Edittext...
    EditText search_edittext;
    private Filter contactFilter;
    //LISTVIEW
    ListView MessageList;
    ProgressDialog pd;

    ArrayList<smsfetch> orinalConlist, smslist;

    Native_DatabaseHelper helper;
    List<smsfetch> allsms;
    myadapter listAdapter;


    // mainlayout declartion
    RelativeLayout MenuLayout_sub, MenuLayout_main, menu_search_edittext,
            Listview_Options;
    // main menu declartion
    RelativeLayout menu_search, menu_more_options, menu_newcompose;
    ImageView menuimage;
    // searchbox
    RelativeLayout menu_search_edit_back;
    EditText menu_search_ET;
    // sub menu
    RelativeLayout menu_private_sms, menu_spam_sms, menu_settings;
    // listview menu
    RelativeLayout Listview_back, Listview_delete, Listview_spam,
            Listview_private;

    String myPackageName;
    DeviceDetailsClass detailsclass;
    RelativeLayout default_application;
    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_private_sms);


        myPackageName = getPackageName();
        detailsclass=new DeviceDetailsClass(this);
        default_application=(RelativeLayout)findViewById(R.id.default_application);
        default_application.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new
                        AlertDialog.Builder(PrivateSMS.this);
                builder.setMessage(
                        "Way2Inbox is not set as your default messaging app. Do you want to set it default?")
                        .setCancelable(false)
                        .setTitle("Alert!")
                        .setNegativeButton("No",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        default_application.setVisibility(View.GONE);

                                    }
                                }).setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            @TargetApi(19)
                            public void onClick(DialogInterface dialog,
                                                int id) {
                                default_application.setVisibility(View.GONE);
                                Intent intent = new Intent(
                                        Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);

                                intent.putExtra(
                                        Telephony.Sms.Intents.EXTRA_PACKAGE_NAME,
                                        getPackageName());
                                // PrintMsg.setLogerror(ComposeSmsActivity.this,"Package name is :"+getPackageName());
                                startActivity(intent);

                            }
                        });
                builder.show();
            }
        });

        //MAIN LAYOUT DECLARATIONS:
        Listview_Options            =(RelativeLayout)findViewById(R.id.Private_List_Options);
        list_menu               =(RelativeLayout)findViewById(R.id.Private_list_menu);
        menu_search_edittext   =(RelativeLayout)findViewById(R.id.Private_search_edittext);

        //SUB MAIN LAYOUT DECLARATIONS...
        Listview_back        =(RelativeLayout)findViewById(R.id.Private_list_options_back);
        Listview_delete          =(RelativeLayout)findViewById(R.id.Private_list_opt_delete);
        Listview_spam            =(RelativeLayout)findViewById(R.id.Private_list_opt_spam);
        Listview_private       =(RelativeLayout)findViewById(R.id.Private_list_opt_unprivate);
        menu_search                   =(RelativeLayout)findViewById(R.id.Private_search);
        Private_back             =(RelativeLayout)findViewById(R.id.Private_back);
        menu_search_edit_back    =(RelativeLayout)findViewById(R.id.Private_search_back);

        MessageList                  =(ListView)findViewById(R.id.PrivateList);
        menu_search_ET            = (EditText) findViewById(R.id.Private_search_edittextfIeld);


        ActionBar actionBar = getSupportActionBar();
//for color
        actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.AppColor)));

        pd = new ProgressDialog(PrivateSMS.this);

        // main layout's declartion
        MenuLayout_main         = (RelativeLayout) findViewById(R.id.MenuLayout_main);
        menu_search_edittext.setVisibility(View.GONE);
//        MenuLayout_sub          = (RelativeLayout) findViewById(R.id.MenuLayout_sub);

//        // main menu items
        menu_newcompose = (RelativeLayout) findViewById(R.id.menu_newcompose);
//        menu_newcompose.setVisibility(View.GONE);
//        menu_search = (RelativeLayout) findViewById(R.id.menu_search);
//        menu_more_options = (RelativeLayout) findViewById(R.id.menu_more_options);
//        menuimage = (ImageView) findViewById(R.id.menu_image);

        // search box instilisation
        menu_search_edit_back.setOnClickListener(this);




        menu_search_ET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
               // MessageList.setStackFromBottom(true);
                if (count < before) {
                    // We're deleting char so we need to reset the adapter data
                    listAdapter.resetData();
                }
                listAdapter.getFilter().filter(s.toString());
                if(count==0){
                   // MessageList.setStackFromBottom(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


//        menu_newcompose.setOnClickListener(this);

        helper = new Native_DatabaseHelper(this);
        allsms = helper.getAllsms(3,null);
        MessageList.setChoiceMode(MessageList.CHOICE_MODE_MULTIPLE_MODAL);
        listAdapter = new myadapter((ArrayList<smsfetch>) allsms);
        MessageList.setAdapter(listAdapter);
        MessageList.setOnItemClickListener(this);
//        }
        Listview_back.setOnClickListener(this);
        Listview_delete.setOnClickListener(this);
        Listview_spam.setOnClickListener(this);
        Listview_private.setOnClickListener(this);
        menu_search.setOnClickListener(this);
        Private_back.setOnClickListener(this);
    }

    @Override
    public void onResume(){
        super.onResume();
        check_default();
    }
    public void check_default(){
        if(detailsclass.getversion()) {
            if (!detailsclass.getdefaultpackage(myPackageName)) {
                default_application.setVisibility(View.VISIBLE);
            }else{
                default_application.setVisibility(View.GONE);
            }
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();

        inflater.inflate(R.menu.menu_messages, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_settings) {
//            return true;
//        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.
                INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        return true;
    }

    class myadapter extends BaseAdapter implements Filterable {
        ArrayList<smsfetch> con_list;
        SparseBooleanArray mSparseBooleanArray;
        private SparseBooleanArray mSelectedItemsIds;
        public myadapter(ArrayList<smsfetch> con_list) {
            this.con_list = con_list;
            orinalConlist = con_list;
            mSparseBooleanArray = new SparseBooleanArray();
        }

        public ArrayList<String> getCheckedItems() {
            ArrayList<String> mTempArry = new ArrayList<String>();

            for(int i=0;i<con_list.size();i++) {
                if(mSparseBooleanArray.get(i)) {
                    smsfetch fetch=con_list.get(i);
                    mTempArry.add(fetch.getAddress());
                }
            }
            System.out.println("this is original size "+mTempArry.size());
            return mTempArry;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return con_list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return con_list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            holder viewHolder;
            View v = convertView;
            if (convertView == null) {
                LayoutInflater li = (LayoutInflater) PrivateSMS.this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = li.inflate(R.layout.adapter_all_messages, null);
                viewHolder = new holder();
                v.setTag(viewHolder);
            } else {
                viewHolder = (holder) v.getTag();
            }
            viewHolder.name = (TextView) v.findViewById(R.id.sms_name);
            viewHolder.lt_msg = (TextView) v.findViewById(R.id.sms_msg);
            viewHolder.cl_pid = (TextView) v.findViewById(R.id.cl_pid);
            viewHolder.sms_image=(ImageView)v.findViewById(R.id.sms_image);
            viewHolder.imagecheck=(CheckBox)v.findViewById(R.id.checkbox);
            viewHolder.imagecheck.setTag(position);
            viewHolder.imagecheck.setChecked(mSparseBooleanArray.get(position));
            viewHolder.imagecheck.setOnCheckedChangeListener(mCheckedChangeListener);
            if(viewHolder.imagecheck.isChecked()){
                viewHolder.sms_image.setImageResource(R.drawable.user_check);
            }else{
                viewHolder.sms_image.setImageResource(R.drawable.noimage_male);
            }

            smsfetch model = con_list.get(position);
            viewHolder.cl_pid.setText(model.getAddress());
            String name = getContactName(model.getAddress());
            if (name.equals(null)) {
                viewHolder.name.setText(model.getAddress());
            } else {
                viewHolder.name.setText(name);
            }
            viewHolder.lt_msg.setText(model.getMsg());
            //viewHolder.sms_image.setOnClickListener(l);
            // viewHolder.date.setText(model.getTime());
            //viewHolder.sms_image.setImageResource(R.drawable.user);
            if(mSparseBooleanArray.get(position)){
                viewHolder.sms_image.setImageResource(R.drawable.user_check);
            }else{
                viewHolder.sms_image.setImageResource(R.drawable.noimage_male);
            }
//            System.out.println(model.get_person() + "  " + model.get_seen()
//                    + "   " + model.getReadState());
            return v;
        }
        public List<smsfetch> getWorldPopulation() {
            return con_list;
        }

        public void toggleSelection(int position) {
            selectView(position, !mSelectedItemsIds.get(position));
        }

        public void removeSelection() {
            mSparseBooleanArray = new SparseBooleanArray();
            notifyDataSetChanged();
        }

        public void selectView(int position, boolean value) {
            if (value)
                mSelectedItemsIds.put(position, value);
            else
                mSelectedItemsIds.delete(position);
            notifyDataSetChanged();
        }

        public int getSelectedCount() {
            return mSelectedItemsIds.size();
        }

        public SparseBooleanArray getSelectedIds() {
            return mSelectedItemsIds;
        }
        @Override
        public Filter getFilter() {
            if (contactFilter == null)
                contactFilter = new ContactFilter();
            return contactFilter;
        }

        public void resetData() {
            con_list = orinalConlist;
        }

        private class ContactFilter extends Filter {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                // We implement here the filter logic
                if (constraint == null || constraint.length() == 0) {
                    // No filter implemented we return all the list
                    results.values = orinalConlist;
                    results.count = orinalConlist.size();
                } else {
                    // We perform filtering operation
                    List<smsfetch> nPlanetList = new ArrayList<smsfetch>();
                    for (smsfetch p : con_list) {
                        if (p.getAddress()
                                .toUpperCase()
                                .startsWith(constraint.toString().toUpperCase()))
                            nPlanetList.add(p);

                    }
                    results.values = nPlanetList;
                    results.count = nPlanetList.size();
                }
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint,
                                          FilterResults results) {
                // Now we have to inform the adapter about the new list filtered
                if (results.count == 0)
                    notifyDataSetInvalidated();
                else {
                    con_list = (ArrayList<smsfetch>) (List<smsfetch>) results.values;
                    notifyDataSetChanged();
                }
            }
        }
        CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
                notifyDataSetChanged();
                if(getCheckedItems().size()==0){
                    list_menu.setVisibility(View.VISIBLE);
                    Listview_Options.setVisibility(View.GONE);
                }else {

                    if (list_menu.getVisibility() == View.VISIBLE) {
                        list_menu.setVisibility(View.GONE);
                        Listview_Options.setVisibility(View.VISIBLE);
                    }
                }
            }
        };
    }

    class holder {

        public TextView name;
        public TextView lt_msg;
        public TextView date, cl_pid;
        public ImageView sms_image;

        public CheckBox imagecheck;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        //smsfetch model=allsms.get(position);
        // smslist
        // =(ArrayList<smsfetch>)sms.getAllSms(Messages.this,"Inbox","Single",model.getAddress());
        // for (int i = 0; i < smslist.size(); i++) {
        // smsfetch model1=smslist.get(i);
        // System.out.println(model.getMsg()+"---"+model.get_person()+"---"+model.getAddress());
        //
        // }
        PrintMsg.SetToast(PrivateSMS.this,"ItemClicked",0);
        TextView tv = (TextView) view.findViewById(R.id.cl_pid);
        TextView tv1=(TextView)view.findViewById(R.id.sms_name);
        Intent i = new Intent(this, ComposeSmsActivity.class);
        i.putExtra("MobileNo", tv.getText().toString());
        if(tv.getText().toString().equals(tv1.getText().toString())){
            i.putExtra("MobileName","Unknown Name");
        }else{
            i.putExtra("MobileName", tv1.getText().toString());}
        startActivity(i);
        finish();

    }

    private class UploadContactTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            SmsDatabase sms = new SmsDatabase(PrivateSMS.this);
//            allsms = sms.getAllSms(Messages.this, "Inbox", "All", null);
            return null;
        }

        @Override
        protected void onPreExecute() {

            pd.show();
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String result) {
            pd.dismiss();
            allsms = helper.getAllsms(1,null);
            System.out.println("this is inserted size " + allsms.size());
            myadapter adapt = new myadapter((ArrayList<smsfetch>) allsms);
            MessageList.setAdapter(adapt);
            super.onPostExecute(result);
        }

    }

    public String getContactName(String phoneNumber) {
        ContentResolver cr = this.getContentResolver();
        Uri uri = Uri.withAppendedPath(
                ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                Uri.encode(phoneNumber));
        Cursor cursor = cr.query(uri,
                new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME },
                null, null, null);
        if (cursor == null) {
            return null;
        }
        String contactName = null;
        if (cursor.moveToFirst()) {
            contactName = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
        } else {
            contactName = phoneNumber;
        }

        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }

        return contactName;
    }




    ArrayList<smsfetch> SpamSMS,PrivateSMS;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.Private_search:
                list_menu.setVisibility(View.GONE);
                menu_search_edittext.setVisibility(View.VISIBLE);
                break;
//            case R.id.menu_newcompose:
//                startActivity(new Intent(this, Contacts.class));
//
//                break;

            case R.id.Private_back:
//                if (MenuLayout_sub.getVisibility() == View.VISIBLE) {
//                    MenuLayout_sub.setVisibility(View.GONE);
//                    menuimage.setImageResource(R.drawable.menu);
//                } else {
//                    MenuLayout_sub.setVisibility(View.VISIBLE);
//                    menuimage.setImageResource(R.drawable.down);
//                }
                startActivity(new Intent(this, Messages.class));
                overridePendingTransition(0, 0);
                finish();
                break;


            case R.id.menu_search_edit_back:
                //MessageList.setStackFromBottom(false);
                menu_search_ET.setText("");
                list_menu.setVisibility(View.VISIBLE);
                menu_search_edittext.setVisibility(View.GONE);


                break;


//            case R.id.menu_private_sms:
//                ArrayList<String> checkedprivate=listAdapter.getCheckedItems();
//                System.out.println("selected size"+checkedprivate.size());
//                for (int i = 0; i < checkedprivate.size(); i++) {
//                    System.out.println("selected address "+checkedprivate.get(i));
//                    helper.insertPrivate_Spam(checkedprivate.get(i),2);
//                }
//
//                ArrayList<String> private_sms=helper.getPrivate_spam(2);
//                PrivateSMS=(ArrayList<smsfetch>) helper.getAllsms(3,"");
//                listAdapter = new myadapter(PrivateSMS);
//                MessageList.setAdapter(listAdapter);
//
//
//                MenuLayout_main.setVisibility(View.VISIBLE);
//                Listview_Options.setVisibility(View.GONE);
//                break;
//
//
//            case R.id.menu_spam_sms:
//                ArrayList<String> checkedspam=listAdapter.getCheckedItems();
//                System.out.println("selected size"+checkedspam.size());
//                for (int i = 0; i < checkedspam.size(); i++) {
//                    System.out.println("selected address "+checkedspam.get(i));
//                    helper.insertPrivate_Spam(checkedspam.get(i),1);
//                }
//
//                ArrayList<String>spam_sms=helper.getPrivate_spam(1);
//
//                SpamSMS=(ArrayList<smsfetch>) helper.getAllsms(2,"");
//                listAdapter = new myadapter(SpamSMS);
//                MessageList.setAdapter(listAdapter);
//
//
//                MenuLayout_main.setVisibility(View.VISIBLE);
//                Listview_Options.setVisibility(View.GONE);
//                break;
//
//
//            case R.id.menu_settings:
//
//
//
//                break;


            case R.id.Private_list_options_back:
                System.out.println("back is selected");
                listAdapter.removeSelection();
                list_menu.setVisibility(View.VISIBLE);
                Listview_Options.setVisibility(View.GONE);
                break;



            case R.id.Private_list_opt_delete:
                ArrayList<String> list = listAdapter.getCheckedItems();
                list_menu.setVisibility(View.VISIBLE);
                Listview_Options.setVisibility(View.GONE);
                Uri deleteUri = Uri.parse("content://sms");
                for (int i = 0; i < list.size(); i++) {

                    PrivateSMS.this.getContentResolver().delete(deleteUri,
                            "address= ?", new String[] { list.get(i) });
                    System.out.println("selected address " + list.get(i));
                }
                SpamSMS=(ArrayList<smsfetch>) helper.getAllsms(1,"");
                listAdapter = new myadapter(SpamSMS);
                MessageList.setAdapter(listAdapter);
                break;


            case R.id.Private_list_opt_spam:
                ArrayList<String> spamlist=listAdapter.getCheckedItems();
                if(spamlist.size()==0){
                    PrintMsg.SetToast(this, getResources().getString(R.string.Listview_opt_spam), 1);
                }else{
                    for (int i = 0; i < spamlist.size(); i++) {
                        helper.updatePrivate_Spam(spamlist.get(i), 1);


                    }

                    SpamSMS=(ArrayList<smsfetch>) helper.getAllsms(3,"");
                    listAdapter = new myadapter(SpamSMS);
                    MessageList.setAdapter(listAdapter);

                    list_menu.setVisibility(View.VISIBLE);
                    Listview_Options.setVisibility(View.GONE);
                }


                break;
            case R.id.Private_list_opt_unprivate:
                ArrayList<String> privatelist=listAdapter.getCheckedItems();
                PrintMsg.setLogerror(PrivateSMS.this,"Private Size list :"+privatelist.size());
                if(privatelist.size()==0){
                    PrintMsg.SetToast(this, getResources().getString(R.string.Listview_opt_private), 1);
                }else{
                    for (int i = 0; i < privatelist.size(); i++) {
                        helper.insertPrivate_Spam(privatelist.get(i), 2);
                    }

                    PrivateSMS=(ArrayList<smsfetch>) helper.getAllsms(3,"");
                    listAdapter = new myadapter(PrivateSMS);
                    MessageList.setAdapter(listAdapter);

                    list_menu.setVisibility(View.VISIBLE);
                    Listview_Options.setVisibility(View.GONE);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub
       // MessageList.setStackFromBottom(true);
        if (count < before) {
            // We're deleting char so we need to reset the adapter data
            listAdapter.resetData();
        }
        listAdapter.getFilter().filter(s.toString());
        if(count==0){
          //  MessageList.setStackFromBottom(false);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub

    }

}